import { createRouter, createWebHashHistory } from 'vue-router'
import storage from '@/utils/storage'
import utils from '@/utils/utils'

import api from '../api'

const routes = [
  {
    name: 'Home',
    path: '/',
    component: () => import('@/components/Home.vue'),
    redirect: '/welcome',
    meta: {
      title: '首页'
    },
    children: [
      {
        name: 'Welcome',
        path: '/welcome',
        meta: {
          title: '欢迎体验Vue3全栈课程'
        },
        component: () => import('@/views/Welcome.vue')
      }
    ]
  },
  {
    name: 'Login',
    path: '/login',
    meta: {
      title: '登录'
    },
    component: () => import('@/views/Login.vue')
  },
  {
    name: 'NotFound',
    path: '/not_found',
    meta: {
      title: '404'
    },
    component: () => import('@/views/NotFound.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

async function loadAsyncRoutes() {
  const userInfo = storage.getItem('userInfo') || {}
  if (userInfo.token) {
    try {
      const { menuList } = await api.getPermissionList()
      const routes = utils.generateRoute(menuList)

      routes.map((route) => {
        const url = `../views/${route.component}.vue`
        route.component = () => import(url)
        router.addRoute('Home', route)
      })
    } catch (error) {
      console.log(error)
    }
  }
}

await loadAsyncRoutes()

// function checkPermission(path) {
//   return !!router.getRoutes().filter((route) => route.path === path).length
// }

router.beforeEach((to, from, next) => {
  // if (checkPermission(to.path)) {
  // console.log('router.hasRoute(to.name) >>> ', to, router.hasRoute(to.name))

  if (router.hasRoute(to.name)) {
    document.title = to.meta.title
    next()
  } else {
    next('/not_found')
  }
})

export default router
